package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.file.FileNameUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.dromara.basic.domain.bo.MemberBo;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.vo.SysOssUploadVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  通用类
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/file")
public class FileUploadController extends BaseController {

    @Value("${fileUpload.profile}")
    private String profile;

    @Autowired
    private ITeachClassService iTeachClassService;

    /**
     * 通用上传（本地）
     */
    @SaIgnore
    @RequestMapping("/upload")
    @ResponseBody
    public R<SysOssUploadVo> upload(@RequestParam("file") MultipartFile file, MemberBo bo) {
        if (!file.isEmpty()) {
            LoginUser loginUser= LoginHelper.getLoginUser();
            if (loginUser == null) {
                throw new ServiceException("请先登录");
            }
            TeachClassVo teachClassVo = iTeachClassService.queryById(bo.getClassId());
            String originalFilename = file.getOriginalFilename();
            String prefix = FileNameUtil.getSuffix(originalFilename);
            String path=profile+"/"+loginUser.getTenantId()+"/"+bo.getFileType();
            File folder = new File(path);
            if (!folder.exists()) {
                    boolean created = folder.mkdirs();
                    if (!created) {
                    throw new ServiceException("文件上传失败");
                }
            }

            if(teachClassVo!=null){
                path=path+"/"+teachClassVo.getGrade();
                File folder2 = new File(path);
                if (!folder2.exists()) {
                    boolean created = folder2.mkdirs();
                    if (!created) {
                        throw new ServiceException("文件上传失败");
                    }
                }
            }

            // 时间格式化格式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            // 获取当前时间并作为时间戳给文件夹命名
            String timeStamp = simpleDateFormat.format(new Date());
            String newFileName = bo.getIdNumber() + "_" +timeStamp +"."+prefix;
            File uploadFile = new File(path, newFileName); // 完整文件路径
            try {
                file.transferTo(uploadFile);
            }catch (Exception e){
                System.out.println(e);
            }
            SysOssUploadVo ossUploadVo=new SysOssUploadVo();
            String url = path+"/"+newFileName;
            ossUploadVo.setUrl(url);
            ossUploadVo.setFileName(newFileName);
            return R.ok("上传成功", ossUploadVo);
        }
        return R.fail("上传失败");
    }
    @SaIgnore
    @RequestMapping("/download")
    public void downloadFile(@RequestParam("url")String url, HttpServletResponse response) throws Exception{
        try {
//            String parentPath = profile;
            File file = new File(url);
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在");
            }
            FileInputStream inputStream = new FileInputStream(file);
            //输出文件
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("文件不存在");
        }catch (Exception e) {
            throw e;
        }
    }
    @SaIgnore
    @RequestMapping("/delete")
    public  R<T> delFile(@RequestParam("url")String url){
//        String parentPath = profile;
        File dest = new File(url);
        if (dest.exists()) {
            Boolean isDelete = FileSystemUtils.deleteRecursively(dest);
            if (!isDelete) {
                throw new ServiceException("删除文件失败!");
            }
        }
        return R.ok("文件删除成功");
    }

}

